'use client'
import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Image from '@tiptap/extension-image'
import { Button } from 'flowbite-react'

const MenuBar = ({ editor }) => {
  if (!editor) return null

  return (
    <div className="border-b p-2 mb-2 flex gap-2 flex-wrap bg-gray-50">
      <Button.Group>
        <Button
          size="sm"
          color={editor.isActive('heading', { level: 2 }) ? 'dark' : 'gray'}
          onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
        >
          标题
        </Button>
        <Button
          size="sm"
          color={editor.isActive('bold') ? 'dark' : 'gray'}
          onClick={() => editor.chain().focus().toggleBold().run()}
        >
          加粗
        </Button>
        <Button
          size="sm"
          color={editor.isActive('italic') ? 'dark' : 'gray'}
          onClick={() => editor.chain().focus().toggleItalic().run()}
        >
          斜体
        </Button>
        <Button
          size="sm"
          color={editor.isActive('strike') ? 'dark' : 'gray'}
          onClick={() => editor.chain().focus().toggleStrike().run()}
        >
          删除线
        </Button>
      </Button.Group>

      <Button.Group>
        <Button
          size="sm"
          color={editor.isActive('bulletList') ? 'dark' : 'gray'}
          onClick={() => editor.chain().focus().toggleBulletList().run()}
        >
          •列表
        </Button>
        <Button
          size="sm"
          color={editor.isActive('orderedList') ? 'dark' : 'gray'}
          onClick={() => editor.chain().focus().toggleOrderedList().run()}
        >
          1.列表
        </Button>
        <Button
          size="sm"
          color={editor.isActive('blockquote') ? 'dark' : 'gray'}
          onClick={() => editor.chain().focus().toggleBlockquote().run()}
        >
          引用
        </Button>
      </Button.Group>

      <Button
        size="sm"
        color="info"
        onClick={() => {
          const url = window.prompt('输入图片URL')
          if (url) {
            editor.chain().focus().setImage({ src: url }).run()
          }
        }}
      >
        插入图片
      </Button>
    </div>
  )
}

export default function TipTapEditor({ content, onChange }) {
  const editor = useEditor({
    extensions: [StarterKit, Image],
    content,
    onUpdate: ({ editor }) => {
      onChange(editor.getHTML())
    },
  })

  return (
    <div className="border rounded-lg overflow-hidden">
      <MenuBar editor={editor} />
      <div className="p-4 min-h-[200px] bg-white">
        <EditorContent editor={editor} className="prose max-w-none" />
      </div>
    </div>
  )
}